var moment = require('moment');
var SignService = require('../service/sign').SignService;
var resErr = require('../lib/util.js').resErr;
var async = require('async');
var DB = require("../lib/db_mysql").DB;
var UserService = require("../service/user").UserService;


exports.views_sign = function(req, res) {
  var user = req.session.user_fw.user;
  var today = moment().format("YYYYMMDD");
  var signService = new SignService();
  var pageSize = req.param("pageSize") || 20;
  var pageNum = req.param("pageNum") || 1;
  signService.getSignLogList(user.id, today, today, pageNum, pageSize, function(err, result) {
    if (err) {
      return resErr(res, err);
    }
    return res.render("sign", {
      "sign_list": result.datas
    });
  })
}

// 显示今天的签到记录
exports.sign_list_today = function(req,res){
  var user = req.session.user_fw.user;
  var user = req.session.user_fw.user;
  var today = moment().format("YYYYMMDD");
  var signService = new SignService();
  var pageSize = req.param("pageSize") || 20;
  var pageNum = req.param("pageNum") || 1;
  signService.getSignLogList(user.id, today, today, pageNum, pageSize, function(err, result) {
    if (err) {
      return resErr(res, err);
    }
    return res.json(result);
  })
}

// 显示今天的签到记录
exports.sign_list = function(req,res){
  var user = req.session.user_fw.user;
  var signService = new SignService();
  var pageSize = req.param("pageSize") || 20;
  var pageNum = req.param("pageNum") || 1;
  var begin_date = req.param("begin_date");
  var end_date = req.param("end_date");
  signService.getSignList(user.id, begin_date, end_date, pageNum, pageSize, function(err, result) {
    if (err) {
      return resErr(res, err);
    }
    return res.json(result);
  })
}

exports.sign = function(req, res) {
  var user = req.session.user_fw.user;
  var user_id = user.id;
  var latitude = req.param('latitude');
  var longitude = req.param('longitude');
  var remark = req.param('remark');
  if (!user_id) {
    return resErr(res,"user_id不能为空！");
  }
  if (!latitude || !longitude) {
    return resErr(res,"经度或纬度不能为空！");
  }
  var IsSign = 0;
  var distance = 0;
  var location_id;
  var sdate = moment().format("YYYYMMDD");
  var stime = moment().format("HHmmss");
  var now = moment().format("YYYY-MM-DD HH:mm:ss");
  async.waterfall([
    function(cb){
      var sql = "select a.location_id from t_location a,t_location_student b where b.user_id = ? and  a.location_id=b.location_id";
      var db = new DB();
      db.queryMap(sql,[user_id],function(err,result){
        if(!result){
          return cb("暂未设置实习地点，签到失败！")
        };
        location_id = result.location_id;
        return cb(null);
      })
    },
    function(cb) { //判断签到距离
      var params1 = [];
      params1.push(longitude);
      params1.push(latitude);
      params1.push(user_id);
      var db = new DB();
      var sql_text = "select GET_DISTANCE(a.longitude,a.latitude,? ,?) as distance,user_id,dis_limit  from t_location a,t_location_student b where b.user_id=? and  a.location_id=b.location_id;";
      var Mysql = db.queryMap(sql_text, params1, function(err, data) {
        if (err) return cb(err);
        if (data.distance > data.dis_limit) {
          return cb("签到距离太远");
        }
        distance = data.distance;
        return cb(null);
      })
    },
    function(cb) { //签到流水 
      var db = new DB();
      var param = {};
      param.user_id = user_id;
      param.sdate = sdate;
      param.stime = stime;
      param.latitude = latitude;
      param.longitude = longitude;
      param.remark = remark;
      param.distance = distance;
      param.dt = now;
      param.location_id = location_id;
      db.insert("t_sign_log",param,function(err){
        return cb(err);
      })
    },
    function(cb) { //判断当天是否已经签到
      var params1 = [];
      params1.push(sdate);
      params1.push(user_id);
      var db = new DB();
      var sql_text = "select count(*) as count from t_sign where init_date = ? and user_id=?;";
      db.query(sql_text, params1, function(err, datas) {
        if (err) return cb(err);
        if (datas.length > 0 && datas[0].count > 0) {
          IsSign = 1
        }
        return cb(null);
      })
    }
  ], function(err) { //更新签到表
    if (err) return resErr(res, err);
    var params2 = [];
    if (IsSign == 0) //表示当天第一次签到
    {
      sql_text = " insert into t_sign set init_date=?,user_id=?,dt_am=?,dt_pm=?,latitude_am=?,longitude_am=?,latitude_pm=?,longitude_pm=?,location_id=?;";
      params2.push(sdate);
      params2.push(user_id);
      params2.push(now);
      params2.push(now);
      params2.push(latitude);
      params2.push(longitude);
      params2.push(latitude);
      params2.push(longitude);
      params2.push(location_id);
    } else //表示当天已经签到过
    {
      sql_text = "update t_sign set dt_pm=?,latitude_pm=?,longitude_pm=? where init_date=curdate() and user_id=?;";
      params2.push(now);
      params2.push(latitude);
      params2.push(longitude);
      params2.push(user_id);
    }
    var db = new DB();
    db.query(sql_text, params2, function(err, datas) {
      if (err) {
        return resErr(res, err);
      }
      return res.json({
        success: true,
        msg: '签到成功！'
      });
    })
  })
}


exports.sign_log_list = function(req, res) {
  var user_id = req.session.user_fw.user.id;
  var begin_date = req.param('begin_date');
  var end_date = req.param('end_date');
  var params = [];
  params.push(user_id);


  var sql_text = "select * from t_sign_log  where user_id= ?  ";
  if (begin_date) {
    sql_text += " and sdate >= ?";
    params.push(begin_date);
  }
  if (end_date) {
    sql_text += " and sdate <= ?";
    params.push(end_date);
  }
  sql_text += ";";
  var db = new DB();
  db.query(sql_text, params, function(err, datas) {
    if (err) return resErr(res, err);
    return res.jsonp(datas);
  });

}